#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
#include <WiFiManager.h> 
#include "DHT.h"
#include "PubSubClient.h"//默认，加载MQTT库文件

#define DHTPIN 3     // 使用IO3引脚连接DHT的信号端，注意：IO3是RXD，配置成普通io后将不能使用串口接受功能
//#define LED_PIN 2    // led PIN esp-01s
const int B_led = 2;

// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 3 (on the right) of the sensor to GROUND (if your sensor has 3 pins)
// Connect pin 4 (on the right) of the sensor to GROUND and leave the pin 3 EMPTY (if your sensor has 4 pins)
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);



String ssid = "";
String password = "";

const char* mqtt_server = "bemfa.com";//默认，MQTT服务器
const int mqtt_server_port = 9501;//默认，MQTT服务器
#define ID_MQTT  "a00658b06d3048684b806fcdf137d9fb"     //修改，你的Client ID
const char*  topic = "DHT2203004";  //主题名字，可在巴法云控制台自行创建，名称随意


WiFiClient espClient;
PubSubClient client(espClient);
WiFiManager wifiManager; // 建立WiFiManager对象

long lastMsg = 0;
char msg[50];
int value = 0;
float temp,humi;


//打开灯泡
void turnOnLed() {
  Serial.println("turn on light");
  digitalWrite(B_led, LOW);
}
//关闭灯泡
void turnOffLed() {
    Serial.println("turn off light");
  digitalWrite(B_led, HIGH);
}



//web 配网
void webConfig()
{
  Serial.println("Wait for web config");
  delay(2000);
  // 等待web配网
  wifiManager.startConfigPortal("ESP_DHTxx");
  ssid = wifiManager.getWiFiSSID();
  password = wifiManager.getWiFiPass();

}


/// @brief 连接wifi
void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  
  ssid = wifiManager.getWiFiSSID();
  password = wifiManager.getWiFiPass();
  WiFi.begin(ssid, password);
  Serial.println(ssid);
  unsigned char i = 0 ;
  while (WiFi.status() != WL_CONNECTED) {
    delay(200); //
    Serial.print(".");
    digitalWrite(B_led, !digitalRead(B_led));
    if(i++ > 50){ // 10S 连接超时
      i = 0;
      webConfig();
    }
  }
  digitalWrite(B_led, 0);
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

/// @brief 收到MQTT的数据
/// @param topic 主题
/// @param payload 数据内容
/// @param length 数据长度
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String Mqtt_Buff = "";
  for (int i = 0; i < length; i++) {
    Mqtt_Buff += (char)payload[i];
  }
  Serial.print(Mqtt_Buff);
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if (Mqtt_Buff == "on") {//如果接收字符on，亮灯
    turnOnLed();//开灯函数

  } else if (Mqtt_Buff == "off") {//如果接收字符off，亮灯
    turnOffLed();//关灯函数
  }
  Mqtt_Buff = "";
}

/// @brief 重连....
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(ID_MQTT)) {
      Serial.println("connected");

      client.subscribe(topic);//修改，修改为你的主题
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

/// @brief MQTT 发布信息
void pubMQTTmsg(){
  
  char jsondata[100]; //创建一个数组用于保存JSON数据
  StaticJsonDocument<150> doc; //建立一个JSON对象

  doc["HUNI"] = humi; //添加JSON数据
  doc["TEMP"] = temp;
  String updata = '#' + String(temp) + '#' + String(humi); 
  serializeJson(doc,jsondata); //数据格式化

  if(client.publish(topic, updata.c_str())){ // 向主题发布信息
    Serial.println("Publish Topic:");Serial.println(topic);
    Serial.println("Publish message:");Serial.println(jsondata); 
    for(int i =0; i<4;i++){
      digitalWrite(B_led, !digitalRead(B_led));
      delay(100);
    }   
  } else {
    Serial.println("Message Publish Failed."); 
  }

}

void setup() {
  Serial.begin(115200);
  Serial.println(F("DHTxx test!"));
  pinMode(B_led,OUTPUT);
  
  dht.begin();

  
  setup_wifi();
  client.setServer(mqtt_server, mqtt_server_port);
  client.setCallback(callback);
}


void loop() {
  // Wait a few seconds between measurements.
    if (!client.connected()) {
    reconnect();
  }
  client.loop();
  delay(3000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  humi = dht.readHumidity();
  // Read temperature as Celsius (the default)
  temp = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(humi) || isnan(temp) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  pubMQTTmsg();
  Serial.print(F("Humidity: "));
  Serial.print(humi);
  Serial.print(F("%  Temperature: "));
  Serial.print(temp);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));

}
